<template>
  <div class="app-container">
    <h4 class="form-header h4">基本信息</h4>
    <el-form ref="form" :model="form" label-width="80px">
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="小说id" prop="nickName">
            <el-input v-model="form.id" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="小说名" prop="userName">
            <el-input v-model="form.bookName" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h4 class="form-header h4">小说章节</h4>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:user:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="this.indexList.length<=0"
          @click="clearBookIndex"
          v-hasPermi="['system:user:remove']"
        >清空
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="indexList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="章节id" align="center" key="id" prop="id" :show-overflow-tooltip="true"/>
      <el-table-column label="字数" align="center" key="wordCount" prop="wordCount" :show-overflow-tooltip="true"/>
      <el-table-column label="是否收费" align="center" key="isVip" prop="sourceName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isVip"
            :active-value="true"
            :inactive-value="false" @change="handleChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="章节名" align="center" key="indexName" prop="indexName" :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.userId !== 1">

          <el-button
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      title="添加章节"
      :visible.sync="indexAddVisible"
      width="50%"
      ref="add-dialog"
      :before-close="handleClose" class="common-dialog">
      <el-form ref="form" :model="addForm" label-width="80px">
        <el-row>
          <el-col :span="8" :offset="2">
            <el-form-item label="小说名" prop="nickName">
              <el-input v-model="addForm.bookName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="爬虫源" prop="userName">
              <el-input  v-model="addForm.crawlName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="crawlIndex.length>0" v-for="(bookIndex,index) in crawlIndex" v-loading="addLoading">
        <el-row style="display: flex;align-items: center;margin-bottom: 10px" >
          <el-col :span="2">
            <el-checkbox/>
          </el-col>
          <el-col :span="18">
            <i style="font-style: normal" class="text-hidden">{{bookIndex.chapterName}}</i>
          </el-col>
          <el-col :span="4" style="cursor: pointer">

            <svg-icon v-if="isLoading(index)" :icon-class="icons.loading" class="loading"/>
            <svg-icon v-else :icon-class="bookIndex.params.isAdd?icons.success:icons.add" @click="addIndex(index,bookIndex)"/>
            <!--          <i v-loading="true" element-loading-spinner="el-icon-loading"></i>-->
          </el-col>

        </el-row>
      </div >
      <div v-if="crawlIndex.length<=0">
        <el-skeleton :rows="6" animated />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {updateCategory, bookIndex, changeIsVip, deleteBookIndex, clearBookIndex} from "@/api/sys/novel";
import {crawlSourceByBookId, updateOrAddCrawlRule,crawlIndexList,addBookIndex} from "@/api/sys/crawl";
import Item from "@/components/CrawlSource/Item"

export default {
  name: "rule",
  dicts: ['sys_normal_disable'],
  components: {
    Item
  },
  data() {
    return {
      indexAddVisible: false,
      // 遮罩层
      loading: true,

      loadingIndex:[],

      addForm:{
        bookName:'',
        crawlBookId:'',
        crawlName:''
      },

      icons:{
        add:'add',
        loading:'loading',
        success:'success'
      },

      addLoading:false,
      crawl:undefined,
      // 选中用户组
      indexIds: [],

      isCanClear: false,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,

      indexList: [],

      bookIndex: undefined,

      crawlIndex:[],

      chapterInfo:{
        bookId:undefined,
        chapterName:undefined,
        indexId:undefined,
        indexNum:undefined,
        chapterHref:undefined
      },

      chapterInfos:[],
      //是否打开抽屉
      drawer: false,
      indexNames: '',
      // 总条数
      total: 0,
      // 用户表格数据
      crawlAndRule: {

      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bookId: undefined,
      },
      form: {
        id: undefined,
        bookName: undefined
      }
    };
  },
  created() {
    const bookId = this.$route.params.bookId;
    if (bookId) {
      this.queryParams.bookId = bookId
      this.getList();
    }
  },
  methods: {
    /** 查询授权用户列表 */
    myIndex(index) {
      return index + 1
    },
    isLoading(index){
      if (this.loadingIndex.length<=0){
        return false
      }
      if (this.loadingIndex.indexOf(index)==-1){
        return false
      }
      return true
    },
    addIndex(index,bookIndex){
      if (bookIndex.params.isAdd){
        return
      }
      this.loadingIndex.unshift(index)
      const data = {}
      data.crawlSourceId = this.bookIndex.crawlSourceId
      data.bookId = this.queryParams.bookId
      this.chapterInfo.bookId = this.queryParams.bookId
      this.chapterInfo.chapterHref = bookIndex.chapterHref
      this.chapterInfo.chapterName  = bookIndex.chapterName
      this.chapterInfo.indexNum = index
      this.chapterInfos.push(this.chapterInfo)
      data.chapterInfos = this.chapterInfos
      addBookIndex(data).then(response=>{
        this.$message.success("添加成功")

      }).finally(()=>{
        this.loadingIndex.remove(index)
        this.chapterInfos=[]
        this.getCrawlIndexList()
      })
    },
    getList() {
      this.loading = true;
      bookIndex(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.bookIndex = response.data
        this.form.id = this.bookIndex.id
        this.form.bookName = this.bookIndex.bookName
        this.indexList = this.bookIndex.bookIndices.records
        this.loading = false
        this.total = this.bookIndex.bookIndices.total
      });

    },
    handleClose(){
      this.indexAddVisible = false
    },
    handleAdd() {
      this.indexAddVisible=true
      crawlSourceByBookId(this.queryParams.bookId).then(response=>{
        this.addForm.bookName = this.form.bookName
        this.crawlAndRule = response.data
        this.addForm.crawlName =this.crawlAndRule.sourceName
        this.addForm.crawlBookId = this.crawlAndRule.params.get(this.queryParams.bookId)
      })
      this.getCrawlIndexList()
    },
    getCrawlIndexList(){
      const query = {
        id:this.queryParams.bookId,
        crawlBookId:this.bookIndex.crawlBookId,
        crawlSourceId:this.bookIndex.crawlSourceId
      }
      this.addLoading=true
      crawlIndexList(query).then(response=>{
        this.crawlIndex = response.data
        this.addLoading=false
      })
    },
    handleChange(row) {
      let text = row.isVip ? "收费" : "免费";
      this.$confirm(`确认要将 【${row.indexName}】修改成${text}吗？`).then(function () {
        return changeIsVip(row.isVip, row.id);
      }).then(() => {
        this.$message.success("修改成功")
        this.getList()
        //this.$Modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status ? false : true;
      });
    },
    handleUpdate(row) {

    },
    clearBookIndex() {
      const bookId = this.queryParams.bookId
      this.$confirm("确定要删除所有的小说章节吗？").then(function () {
        return clearBookIndex(bookId);

      }).then(() => {
        this.$message.success("删除成功")
      }).finally(() => {
        this.getList()
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleDelete(row) {
      const indexIds = row.id || this.indexIds;
      const bookId = this.queryParams.bookId
      this.$confirm(`是否确认删除章节【${row.indexName ? row.indexName : this.indexNames}】的数据项？`).then(function () {
        return deleteBookIndex(bookId, indexIds);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.indexIds = selection.map(item => item.id)
      this.indexNames = ''
      selection.map(item => {
        if (this.indexNames != '') {
          this.indexNames = `${this.indexNames},`
        }
        this.indexNames = `${this.indexNames}${item.indexName}`
      })
      this.multiple = !selection.length
    },
    /** 打开授权用户表弹窗 */
    openSelectUser() {
      this.$refs.select.show();
    },
    formatter(row) {
      if (row.workDirection) {
        return '女频'
      } else {
        return '男频'
      }
    },
    updateCategory(row) {
      const query = {}
      query.id = this.form.bookId || undefined
      query.catId = row.id || undefined
      query.catName = row.name || undefined
      updateCategory(query).then(response => {
        this.getList()
      })
    },
    submitRule() {
      updateOrAddCrawlRule(this.form).then(response => {
        this.$message.success("更新成功")
        this.getList()
      })
    }
  }
};
</script>
